#coding=utf-8
import status
from apps import apps, reverse_port, http_ports

# 检查 Interner 连通状态
http_available = []
reverse_available = []

for a in apps:
    if status.check_connect(a, 'http'): http_available.append(a)
    if status.check_connect(a, 'reverse'): reverse_available.append(a)

print http_available
print reverse_available

#检查 proxy 进程运行情况
result = status.check_running_proxy()
r = result['reverse']
if r and r[0] not in reverse_available:
    status.stop_proxy(r[-1])
    
http_running = result['http']
for p in http_running:
    if p[0] not in http_available:
        status.stop_proxy(p[-1])
    
result = status.check_running_proxy()
#始终保证有一个reverse proxy app在正常运行
r = result['reverse']
if not r:
    appid = reverse_available[0]
    status.start_proxy(appid, reverse_port, 'reverse')
    
http_running = result['http']
n = 5 - len(http_running)
if n > 0:
    http_running_appids = [p[0] for p in http_running]
    http_running_ports = [p[-2] for p in http_running]
    
    not_running_appids = list(set(http_available) - set(http_running_appids))[:n]
    not_use_ports = list(set(http_ports) - set(http_running_ports))
    
    for i in range(len(not_running_appids)):
        status.start_proxy(not_running_appids[i], not_use_ports[i], 'http')
        



